package leetcode.f1t100;

/**
 * 顺时针内卷输出N阶矩阵
 * https://leetcode.com/problems/spiral-matrix-ii/
 *
 * @Author lichongxiao
 * @Date 2022/10/25 14:22
 */
public class Q59_SpiralMartixII {
    public int[][] generateMatrix(int n) {
        int[][] ans = new int[n][n];
        int colBegin = 0, rowBegin = 0, colEnd = n - 1, rowEnd = n - 1, cur = 0, turn = 0;
        while (colBegin <= colEnd && rowBegin <= rowEnd) {
            switch (turn) {
                case 0:
                    for (int i = rowBegin; i <= rowEnd; i++) {
                        ans[colBegin][i] = ++cur;
                    }
                    colBegin++;
                    break;
                case 1:
                    for (int i = colBegin; i <= colEnd; i++) {
                        ans[i][rowEnd] = ++cur;
                    }
                    rowEnd--;
                    break;
                case 2:
                    for (int i = rowEnd; i >= rowBegin; i--) {
                        ans[colEnd][i] = ++cur;
                    }
                    colEnd--;
                    break;
                case 3:
                    for (int i = colEnd; i >= colBegin; i--) {
                        ans[i][rowBegin] = ++cur;
                    }
                    rowBegin++;
                    break;
            }
            turn = (turn + 1) % 4;
        }
        return ans;
    }

    public static void main(String[] args) {
        Q59_SpiralMartixII bean = new Q59_SpiralMartixII();
        int[][] martix = bean.generateMatrix(4);
        for (int[] ints : martix) {
            for (int num : ints) {
                System.out.print(num+ "  ");
            }
            System.out.println();
        }
    }
}
